package com.zx.sys.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zx.sys.constast.SysConstast;
import com.zx.sys.domain.Menu;
import com.zx.sys.domain.Role;
import com.zx.sys.mapper.MenuMapper;
import com.zx.sys.mapper.RoleMapper;
import com.zx.sys.mapper.RoleMapper;
import com.zx.sys.service.RoleService;
import com.zx.sys.service.RoleService;
import com.zx.sys.utils.DataGridView;
import com.zx.sys.utils.TreeNode;
import com.zx.sys.utils.TreeNodeBuilder;
import com.zx.sys.vo.RoleVo;
import com.zx.sys.vo.RoleVo;

@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private MenuMapper menuMapper;

	@Override
	public DataGridView queryAllRole(RoleVo roleVo) {
		Page<Object> page = PageHelper.startPage(roleVo.getPage(), roleVo.getLimit());
		List<Role> data = roleMapper.queryAllRole(roleVo); 
		return new DataGridView(page.getTotal(), data);
	}

	@Override
	public void addRole(RoleVo RoleVo) {
		roleMapper.insertSelective(RoleVo);
	}

	@Override
	public void updateRole(RoleVo RoleVo) {
		roleMapper.updateByPrimaryKeySelective(RoleVo);
	}

	@Override
	public void deleteRole(Integer roleid) {
		roleMapper.deleteByPrimaryKey(roleid);
		roleMapper.deleteRoleMenuByRid(roleid);
		roleMapper.deleteRoleUserByRid(roleid);
	}

	@Override
	public void deleteBatchRole(Integer[] ids) {
		for (Integer id : ids) {
			deleteRole(id);
		}
	}

	@Override
	public DataGridView initRoleMenuTreeJson(Integer roleid) {
		Menu menu = new Menu();
		menu.setAvailable(SysConstast.AVAILABLE_TRUE);
		List<Menu> allMenus = menuMapper.queryAllMenu(menu);
		List<Menu> roleMenu = menuMapper.queryMenuByRoleId(SysConstast.AVAILABLE_TRUE, roleid);
		
		List<TreeNode> list = new ArrayList<TreeNode>();
		for (Menu aMenu : allMenus) {
			String title = aMenu.getTitle();
			Integer id = aMenu.getId();
			Integer pid = aMenu.getPid();
			String checkArr = "0";
			for (Menu rMenu : roleMenu) {
				if(rMenu.getId()==aMenu.getId()){
					checkArr = "1";
				}
			}
			list.add(new TreeNode(id, pid, title, checkArr));
		}
		
		return new DataGridView(0l,list);
	}

	@Override
	public void saveRoleMenu(RoleVo roleVo) {
		Integer rid = roleVo.getRoleid();
		Integer[] mids = roleVo.getIds();
		
		roleMapper.deleteRoleMenuByRid(rid);
		if(mids!=null){
			for (Integer mid : mids) {
				roleMapper.insertRoleMenu(rid,mid);
			}
		}
	}
}
